package org.jader.bolao;

public class GamePlayer {
	private static final int TOTAL_BALLS = 4*6;
	
	private Game owner = null;
	private Player player = null;
	private int[] balls = null;
	private int sum = 0;
	private boolean summed = false;
	
	protected GamePlayer(Game g, Player p) {
		this.owner  = g;
		this.player = p;
	}
	
	public Player player() {
		return this.player;
	}
	
	public int getSum() {
		return this.sum;
	}
	
	public boolean isDetailed() {
		return this.balls != null;
	}
	
	public int[] getBalls() {
		return this.balls;
	}
	
	public boolean isSummed() {
		return this.summed;
	}
	
	public void setBall(int index, int value) {
		if (index >= 0 && index < balls.length) {
			if (value >= 0 && value < 10) {
				if (this.balls == null) this.balls = new int[TOTAL_BALLS];
				this.balls[index] = value;
				owner.firePropertyChange(this, "ball");
			}
			recalculateSum();
		}
	}
	
	private void recalculateSum() {
		int liveSum = 0;
		for (int i=0; i<this.balls.length; i++) {
			if (i%6 != 0) {
				liveSum += this.balls[i];
			}
		}
		this.sum = liveSum;
	}

	public void setSum(int value) {
		if (isDetailed()) return;
		if (this.sum == value) return;
		this.sum = value;
		owner.firePropertyChange(this, "sum");
	}
	
	public void setDetailed(boolean b) {
		if ((this.balls == null) == b) return;
		if (b) {
			this.balls = new int[TOTAL_BALLS];
			this.sum = 0;
		}
		else
			this.balls = null;
		owner.firePropertyChange(this, "detailed");
	}
	
	public void setSummed(boolean b) {
		if (this.summed == b) return;
		this.summed = b;
		owner.firePropertyChange(this, "summed");
	}
}
